package com.freecat.gpstest;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.freecat.adapter.GpsAddressItemAdater;
import com.freecat.database.DBHelper;
import com.freecat.database.SQLFunction;
import com.freecat.entity.gpsitem;
import com.freecat.utils.ExcelUtil;
import com.freecat.utils.MapFixUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    Context mContext;

    TextView tv_gps_address;
    TextView tv_gps_loc;
    TextView tv_gps_time;
    TextView tv_gps_test;

    Button btn_save;
    Button btn_excel_out;

    ListView lv_gps_local;

    MapView bmapView;


    double Endlongitude;
    double Endlatitude;
    String Endaddress;
    String Stardaddress;
    String address;
    double Plongitude;
    double Platitude;
    double marslongitude;
    //
    double marslatitude;


    private BaiduMap baiduMap;

    private LatLng latLng;

    boolean isFirstLoc=true;
    String gpsaddress="gpsaddress";


    LocationClientOption locationOption = new LocationClientOption();

    private LocationClient locationClient;


    public static double pi = 3.1415926535897932384626;
    SQLFunction function = new SQLFunction();

    DBHelper dbHelper;

    String time=null;

    String hight;

    List<gpsitem> gpslist;
    List<gpsitem> exc_gpslist;

    GpsAddressItemAdater RMA;


    AlertDialog dialog;




    gpsitem pb;


    EditText ed_diag_xfsbh=null;
    EditText ed_diag_locy=null;
    EditText ed_diage_locx=null;
    EditText ed_diag_hight=null;
    EditText ed_diag_sdwskgg=null;
    EditText ed_diag_gwzj=null;
    EditText ed_diag_gwyl=null;
    EditText ed_diag_jdmc=null;
    EditText ed_diag_wzms=null;
    EditText ed_diag_bz=null;
    View view=null;

    Spinner sp_diag_fzxs=null;
    Spinner sp_diag_gwxs=null;
    Spinner sp_diag_kyzt=null;

    ArrayAdapter fzxs_adapter=null;
    ArrayAdapter gwxs_adapter=null;
    ArrayAdapter kyzt_adapter=null;

    String fzxs;
    String gwxs;
    String kyzt;

    String rq;

    String rq1;

    String db_rq;
    int db_count;
    int count=0;

    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext=this;
        sharedPreferences= getSharedPreferences("gpstest",Context.MODE_PRIVATE);
        createdb();
        SDKInitializer.initialize(getApplicationContext());
        SDKInitializer.setCoordType(CoordType.BD09LL);

        setContentView(R.layout.activity_main);
        intiview();
        initxfsbh();
        initMap();


    }

    //获取当天的最新一条数据
    /*
    * 先读取是否有数据
    * 如果有就取出来，如果没有，是为当天地一条，那就默认为0001
    * 需要存储一个日期，该日期
    * */
    public void initxfsbh(){

        //初始化本地缓存


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");// HH:mm:ss
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        rq=simpleDateFormat.format(date);

        //先获取本地数据
        rq1=sharedPreferences.getString("rq","");
        SharedPreferences.Editor editor = sharedPreferences.edit();

        //如果本地数据日期不等于NULL 如果日期为NULL，就直接初始缓存数据到日期，并写入为1
        if (rq1!=null){

            //如果是当天日期，如果不是当天日期，那么就把当日日期缓存到本地，
            if(rq.equals(rq1)){



            }else {

                //步骤2： 实例化SharedPreferences.Editor对象
                //步骤3：将获取过来的值放入文件
                //如果今天第一次启动，获取到的日期不一样，那么缓存为1
                editor.putString("rq",rq);
                editor.putInt("count",1);
            }
        }else {

            editor.putString("rq",rq);
            editor.putInt("count",1);

        }

        editor.commit();

//
//        //步骤2： 实例化SharedPreferences.Editor对象
//        //步骤3：将获取过来的值放入文件
//        editor.putString("rq","tom");
//        editor.putString("age", "");
        //步骤4：提交

//        editor.remove("name");
//
//        editor.clear();


    }
    public  void createdb(){
        dbHelper = new DBHelper(mContext);
        SQLiteDatabase db1 = dbHelper.getReadableDatabase();
//        Log.i(TAG, "initView: StartActivity"+db1.getPath().toString());
        dbHelper.close();

    }

    //初始化控件
    public void intiview(){

        tv_gps_address=findViewById(R.id.tv_gps_address);
        tv_gps_loc=findViewById(R.id.tv_gps_loc);
        tv_gps_time=findViewById(R.id.tv_gps_time);
        tv_gps_test=findViewById(R.id.tv_gps_test);

        btn_save=findViewById(R.id.btn_save);
        btn_excel_out=findViewById(R.id.btn_excel_out);

        lv_gps_local=findViewById(R.id.lv_gps_local);
        bmapView=findViewById(R.id.bmapView);

        gpslist=new ArrayList<>();
        gpslist=initdata_load_ALL();
        RMA=new GpsAddressItemAdater(mContext,gpslist);
        lv_gps_local.setAdapter(RMA);
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                locationClient.start();
//                Toast toast=Toast.makeText(getApplicationContext(), "获取数据"+Plongitude+"----"+Platitude, Toast.LENGTH_SHORT);
//                toast.show();
//                System.out.println("获取数据"+Plongitude+"----"+Platitude);
//                initMap();
                 db_rq=sharedPreferences.getString("rq","");
                db_count=sharedPreferences.getInt("count",0);
//                System.out.println(test+"=========="+testcount);
                tv_gps_test.setText(db_rq+"===="+db_count);

                if (address!=null&&time!=null&&marslatitude!=0&&marslongitude!=0&&Platitude!=0&&Plongitude!=0){
                    gpsitem gi=new gpsitem();
                    gi.setAddress(address);
                    gi.setTime(time);
                    gi.setHight(hight);
                    gi.setBlat(String.valueOf(Platitude));
                    gi.setBlon(String.valueOf(Plongitude));
                    gi.setGlat(String.valueOf(marslatitude));
                    gi.setGlon(String.valueOf(marslongitude));
                    gi.setStatus("1");
                    tv_gps_address.setText(address);
                    tv_gps_loc.setText(Plongitude+"--"+Platitude);
                    tv_gps_time.setText(NewXFSBH("01"));

//                    gpsadd(gi);
//                    gpslist.add(gi);
//                    RMA=new GpsAddressItemAdater(mContext,gpslist);
//                    lv_gps_local.setAdapter(RMA);
                    showDialog(gi);
                }else {
                    Toast toast1=Toast.makeText(getApplicationContext(), "没有获取到GPS数据，请检查", Toast.LENGTH_SHORT);
                    toast1.show();
                }


            }
        });
        btn_excel_out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                showDialog_db_clear1();

            }
        });


    }


//    public  void gpsadd(gpsitem gi){
//
//        //address VARCHAR,TIME TEXT,glat TEXT,glon TEXT,blat TEXT,blon TEXT,Status TEXT
//        String sql = "insert into "+gpsaddress+" (address,TIME,glat,glon,blat,blon,Status) values (?,?,?,?,?,?,?)";
//        Object[] data = {gi.getAddress() ,gi.getTime() ,gi.getGlat(),gi.getGlon(),gi.getBlat(),gi.getGlon(),gi.getStatus()};
//
//        function.insert(mContext,data,sql);
//    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        bmapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        bmapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        bmapView.onPause();
    }

    private void initMap() {
        //获取地图控件引用
        baiduMap = bmapView.getMap();
        //普通地图
        baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        baiduMap.setMyLocationEnabled(true);
        //默认显示普通地图
        baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        //开启交通图
        //mBaiduMap.setTrafficEnabled(true);
        //开启热力图
        //mBaiduMap.setBaiduHeatMapEnabled(true);
        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        initLocationOption();
    }


    private void initLocationOption() {
//定位服务的客户端。宿主程序在客户端声明此类，并调用，目前只支持在主线程中启动
        locationClient = new LocationClient(getApplicationContext());
//声明LocationClient类实例并配置定位参数
//        LocationClientOption locationOption = new LocationClientOption();
        MyLocationListener myLocationListener = new MyLocationListener();
//注册监听函数
        locationClient.registerLocationListener(myLocationListener);

        locationOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
//        locationOption.setCoorType("bd09ll");
        //可选，默认false，设置是否开启Gps定位
        locationOption.setOpenGps(true);
//可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        locationOption.setScanSpan(3000);
//可选，设置是否需要地址信息，默认不需要
        locationOption.setIsNeedAddress(true);
//可选，设置是否需要地址描述
        locationOption.setIsNeedLocationDescribe(false);
//可选，设置是否需要设备方向结果
        locationOption.setNeedDeviceDirect(true);
//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        locationOption.setLocationNotify(false);
//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        locationOption.setIgnoreKillProcess(true);
//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        locationOption.setIsNeedLocationPoiList(true);
//可选，默认false，设置是否收集CRASH信息，默认收集
        locationOption.SetIgnoreCacheException(false);
//可选，默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
        locationOption.setIsNeedAltitude(true);
//设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者，该模式下开发者无需再关心定位间隔是多少，定位SDK本身发现位置变化就会及时回调给开发者
        locationOption.setOpenAutoNotifyMode();
////设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者
//        locationOption.setOpenAutoNotifyMode(1000,10, LocationClientOption.LOC_SENSITIVITY_HIGHT);
        locationClient.setLocOption(locationOption);
        locationClient.start();
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
             time = location.getTime();

            System.out.println("时间获取"+time);

            address = location.getAddress().address;
            hight=String.valueOf(location.getAltitude());
//             address = "我是测试地址标识";
            //获取的是火星坐标
            double longitude = location.getLongitude();
//
            double latitude = location.getLatitude();


            marslongitude=longitude;
            marslatitude=latitude;
//            Plongitude=location.getLongitude();
//            Platitude= location.getLatitude();
            // 转换为百度坐标
            HashMap marsTobaidu= MapFixUtil.marsTobaidu(longitude,latitude);
            double longitude1= (double) marsTobaidu.get("baidu_point_lon");
            double latitude1= (double) marsTobaidu.get("baidu_point_lat");


            //            String address = "当前坐标"+longitude1+"--"+latitude1;
//              String address = "当前坐标"+longitude+"--"+latitude;
//              ToastUtils.showShort(address);

//            //最后存储的是转换后的百度坐标
//            longitude = longitude1;
//            latitude = latitude1;

            Plongitude=longitude1;

            Platitude= latitude1;

            System.out.println("我是火星坐标"+longitude+"我是火星坐标"+latitude+"我是百度坐标"+longitude1+"我是百度坐标"+latitude1);


            latLng = new LatLng(location.getLatitude(), location.getLongitude());
            // 构造定位数据
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            // 设置定位数据
            baiduMap.setMyLocationData(locData);
            // 当不需要定位图层时关闭定位图层
            //mBaiduMap.setMyLocationEnabled(false);
//            if (isFirstLoc) {
//                isFirstLoc = false;
                LatLng ll = new LatLng(Platitude,
                        Plongitude);
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                if (location.getLocType() == BDLocation.TypeGpsLocation) {
                    // GPS定位结果
//                    Toast.makeText(MainActivity.this, location.getAddrStr(), Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                    // 网络定位结果
//                    Toast.makeText(MainActivity.this, location.getAddrStr(), Toast.LENGTH_SHORT).show();

                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
                    // 离线定位结果
//                    Toast.makeText(MainActivity.this, location.getAddrStr(), Toast.LENGTH_SHORT).show();

                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    Toast.makeText(MainActivity.this, "服务器错误，请检查", Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    Toast.makeText(MainActivity.this, "网络错误，请检查", Toast.LENGTH_SHORT).show();
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    Toast.makeText(MainActivity.this, "手机模式错误，请检查是否飞行", Toast.LENGTH_SHORT).show();
                }

//            }

        }
    }


    public List<gpsitem> initdata(){

        Log.i("TAG:","查询数据！");
        String where1= new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(new Date()).toString();

        String where2= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(new Date()).toString();

        System.out.println("where1+where2"+where1+"==="+where2);
        ArrayList<HashMap<String ,String>> list = new ArrayList<>();
        //heartdata>? and heartdata<?
        String sql = "select * from gpsaddress where TIME between  ? and ?";
//         String sql = "select * from resevermessage where time like ? and info like ?";

        list = function.query_get_time(mContext,where1,where2,sql);
//        list = function.query(mContext,where1,where2,sql);
        List<gpsitem> plist=new ArrayList();
        if(list!=null){
            for(int i = 0 ; i<list.size();i++){
                Log.i("TAG:","从数据库中拿到的数据 _ID为：" +list.get(i).get("id"));
                Log.i("TAG:","从数据库中拿到的数据name为：" + list.get(i).get("address"));
                Log.i("TAG:","从数据库中拿到的数据time为：" + list.get(i).get("TIME"));
                Log.i("TAG:","从数据库中拿到的数据glat为：" + list.get(i).get("glat"));
                Log.i("TAG:","从数据库中拿到的数据glon为：" + list.get(i).get("glon"));
                Log.i("TAG:","从数据库中拿到的数据blat为：" + list.get(i).get("blat"));
                Log.i("TAG:","从数据库中拿到的数据blon为：" + list.get(i).get("blon"));
                Log.i("TAG:","从数据库中拿到的数据info为：" + list.get(i).get("status"));


//                this.id = id;
//                this.address = address;
//                this.time = time;
//                this.glat = glat;
//                this.glon = glon;
//                this.blat = blat;
//                this.blon = blon;
//                Status = status;
                gpsitem pm=new gpsitem();

                pm.setId(Integer.valueOf(list.get(i).get("id")));
                pm.setAddress(list.get(i).get("address"));
                pm.setTime(list.get(i).get("TIME"));
                pm.setGlat(list.get(i).get("glat"));
                pm.setGlon(list.get(i).get("glon"));
                pm.setBlat(list.get(i).get("blat"));
                pm.setBlon(list.get(i).get("blon"));
                pm.setXfsbh(list.get(i).get("xfsbh"));
                pm.setLocx(list.get(i).get("locx"));
                pm.setLocy(list.get(i).get("locy"));
                pm.setHight(list.get(i).get("hight"));
                pm.setPlace(list.get(i).get("place"));
                pm.setSdcskjkgg(list.get(i).get("sdcskjkgg"));
                pm.setGwzj(list.get(i).get("gwzj"));
                pm.setGwyl(list.get(i).get("gwyl"));
                pm.setGwxs(list.get(i).get("gwxs"));
                pm.setKyzt(list.get(i).get("kyzt"));
                pm.setJdmc(list.get(i).get("jdmc"));
                pm.setWzms(list.get(i).get("wzmc"));
                pm.setBz(list.get(i).get("bz"));


                plist.add(pm);

            }

            return plist;

        }else {
            Log.i("TAG:","从数据库中没有拿到数据！");
        }

        return  null;
    }


    /*
    获取数据库里的所有数据
    没有导出的所有数据
    * */
    public List<gpsitem> initdata_load_ALL(){

        Log.i("TAG:","查询数据！");
        String where1= new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(new Date()).toString();

        String where2= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(new Date()).toString();

        System.out.println("where1+where2"+where1+"==="+where2);
        ArrayList<HashMap<String ,String>> list = new ArrayList<>();
        //heartdata>? and heartdata<?
        /*
        *   //顺序
            sql = "select * from "+MySQL.TABLE_BURNER+" order by _id asc";
	     //倒序
            sql = "select * from "+MySQL.TABLE_BURNER+" order by _id desc";
        * */
         String sql = "select * from gpsaddress order by id desc";
//         String sql = "select * from resevermessage where time like ? and info like ?";

        list = function.query_get_all(mContext,sql);
//        list = function.query(mContext,where1,where2,sql);
        List<gpsitem> plist=new ArrayList();
        if(list!=null){
            for(int i = 0 ; i<list.size();i++){
                Log.i("TAG:","从数据库中拿到的数据 _ID为：" +list.get(i).get("id"));
                Log.i("TAG:","从数据库中拿到的数据address为：" + list.get(i).get("address"));
                Log.i("TAG:","从数据库中拿到的数据time为：" + list.get(i).get("TIME"));
                Log.i("TAG:","从数据库中拿到的数据glat为：" + list.get(i).get("glat"));
                Log.i("TAG:","从数据库中拿到的数据glon为：" + list.get(i).get("glon"));
                Log.i("TAG:","从数据库中拿到的数据blat为：" + list.get(i).get("blat"));
                Log.i("TAG:","从数据库中拿到的数据blon为：" + list.get(i).get("blon"));
                Log.i("TAG:","从数据库中拿到的数据status为：" + list.get(i).get("status"));
                Log.i("TAG:","从数据库中拿到的数据xfsbh为：" + list.get(i).get("xfsbh"));
//                this.id = id;
//                this.address = address;
//                this.time = time;
//                this.glat = glat;
//                this.glon = glon;
//                this.blat = blat;
//                this.blon = blon;
//                Status = status;
                   /*
                 * id INTEGER PRIMARY KEY AUTOINCREMENT,
                 * xfsbh TEXT,
                 * address TEXT,
                 * TIME TEXT,
                 * glat TEXT,
                 * glon TEXT,
                 * blat TEXT,
                 * blon TEXT,
                 * Status TEXT,
                 * locx TEXT,
                 * locy TEXT,
                 * hight TEXT,
                 * place TEXT,
                 * sdcskjkgg TEXT,
                 * gwzj TEXT,
                 * gwyl TEXT,
                 * gwxs TEXT,
                 * kyzt TEXT,
                 * jdmc TEXT,
                 * wzms TEXT,
                 * bz TEXT
                 * */
                gpsitem pm=new gpsitem();

                pm.setId(Integer.valueOf(list.get(i).get("id")));
                pm.setAddress(list.get(i).get("address"));
                pm.setTime(list.get(i).get("TIME"));
                pm.setGlat(list.get(i).get("glat"));
                pm.setGlon(list.get(i).get("glon"));
                pm.setBlat(list.get(i).get("blat"));
                pm.setBlon(list.get(i).get("blon"));
                pm.setXfsbh(list.get(i).get("xfsbh"));
                pm.setLocx(list.get(i).get("locx"));
                pm.setLocy(list.get(i).get("locy"));
                pm.setHight(list.get(i).get("hight"));
                pm.setPlace(list.get(i).get("place"));
                pm.setSdcskjkgg(list.get(i).get("sdcskjkgg"));
                pm.setGwzj(list.get(i).get("gwzj"));
                pm.setGwyl(list.get(i).get("gwyl"));
                pm.setGwxs(list.get(i).get("gwxs"));
                pm.setKyzt(list.get(i).get("kyzt"));
                pm.setJdmc(list.get(i).get("jdmc"));
                pm.setWzms(list.get(i).get("wzmc"));
                pm.setBz(list.get(i).get("bz"));


                plist.add(pm);

            }

            return plist;

        }else {
            Log.i("TAG:","从数据库中没有拿到数据！");
        }

        return  null;
    }



    public List<gpsitem> initdata_load_ALL_asc(){

        Log.i("TAG:","查询数据！");
        String where1= new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(new Date()).toString();

        String where2= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(new Date()).toString();

        System.out.println("where1+where2"+where1+"==="+where2);
        ArrayList<HashMap<String ,String>> list = new ArrayList<>();
        //heartdata>? and heartdata<?
        /*
        *   //顺序
            sql = "select * from "+MySQL.TABLE_BURNER+" order by _id asc";
	     //倒序
            sql = "select * from "+MySQL.TABLE_BURNER+" order by _id desc";
        * */
        String sql = "select * from gpsaddress order by id asc";
//         String sql = "select * from resevermessage where time like ? and info like ?";

        list = function.query_get_all(mContext,sql);
//        list = function.query(mContext,where1,where2,sql);
        List<gpsitem> plist=new ArrayList();
        if(list!=null){
            for(int i = 0 ; i<list.size();i++){
                Log.i("TAG:","从数据库中拿到的数据 _ID为：" +list.get(i).get("id"));
                Log.i("TAG:","从数据库中拿到的数据address为：" + list.get(i).get("address"));
                Log.i("TAG:","从数据库中拿到的数据time为：" + list.get(i).get("TIME"));
                Log.i("TAG:","从数据库中拿到的数据glat为：" + list.get(i).get("glat"));
                Log.i("TAG:","从数据库中拿到的数据glon为：" + list.get(i).get("glon"));
                Log.i("TAG:","从数据库中拿到的数据blat为：" + list.get(i).get("blat"));
                Log.i("TAG:","从数据库中拿到的数据blon为：" + list.get(i).get("blon"));
                Log.i("TAG:","从数据库中拿到的数据status为：" + list.get(i).get("status"));
                Log.i("TAG:","从数据库中拿到的数据xfsbh为：" + list.get(i).get("xfsbh"));
//                this.id = id;
//                this.address = address;
//                this.time = time;
//                this.glat = glat;
//                this.glon = glon;
//                this.blat = blat;
//                this.blon = blon;
//                Status = status;
                /*
                 * id INTEGER PRIMARY KEY AUTOINCREMENT,
                 * xfsbh TEXT,
                 * address TEXT,
                 * TIME TEXT,
                 * glat TEXT,
                 * glon TEXT,
                 * blat TEXT,
                 * blon TEXT,
                 * Status TEXT,
                 * locx TEXT,
                 * locy TEXT,
                 * hight TEXT,
                 * place TEXT,
                 * sdcskjkgg TEXT,
                 * gwzj TEXT,
                 * gwyl TEXT,
                 * gwxs TEXT,
                 * kyzt TEXT,
                 * jdmc TEXT,
                 * wzms TEXT,
                 * bz TEXT
                 * */
                gpsitem pm=new gpsitem();

                pm.setId(Integer.valueOf(list.get(i).get("id")));
                pm.setAddress(list.get(i).get("address"));
                pm.setTime(list.get(i).get("TIME"));
                pm.setGlat(list.get(i).get("glat"));
                pm.setGlon(list.get(i).get("glon"));
                pm.setBlat(list.get(i).get("blat"));
                pm.setBlon(list.get(i).get("blon"));
                pm.setXfsbh(list.get(i).get("xfsbh"));
                pm.setLocx(list.get(i).get("locx"));
                pm.setLocy(list.get(i).get("locy"));
                pm.setHight(list.get(i).get("hight"));
                pm.setPlace(list.get(i).get("place"));
                pm.setSdcskjkgg(list.get(i).get("sdcskjkgg"));
                pm.setGwzj(list.get(i).get("gwzj"));
                pm.setGwyl(list.get(i).get("gwyl"));
                pm.setGwxs(list.get(i).get("gwxs"));
                pm.setKyzt(list.get(i).get("kyzt"));
                pm.setJdmc(list.get(i).get("jdmc"));
                pm.setWzms(list.get(i).get("wzmc"));
                pm.setBz(list.get(i).get("bz"));


                plist.add(pm);

            }

            return plist;

        }else {
            Log.i("TAG:","从数据库中没有拿到数据！");
        }

        return  null;
    }


    private void showDialog(final gpsitem gi){

        System.out.println("弹出对话框");


        view = LayoutInflater.from(mContext).inflate(R.layout.gps_itme_custom_diag,null,false);
        dialog = new AlertDialog.Builder(mContext).setView(view).create();

        ed_diag_xfsbh=view.findViewById(R.id.ed_diag_xfsbh);
        ed_diag_locy=view.findViewById(R.id.ed_diag_locy);
        ed_diage_locx=view.findViewById(R.id.ed_diage_locx);
        ed_diag_hight=view.findViewById(R.id.ed_diag_hight);
        ed_diag_sdwskgg=view.findViewById(R.id.ed_diag_sdwskgg);
        ed_diag_gwzj=view.findViewById(R.id.ed_diag_gwzj);
        ed_diag_gwyl=view.findViewById(R.id.ed_diag_gwyl);
        ed_diag_jdmc=view.findViewById(R.id.ed_diag_jdmc);
        ed_diag_wzms=view.findViewById(R.id.ed_diag_wzms);
        ed_diag_bz=view.findViewById(R.id.ed_diag_bz);
        sp_diag_fzxs=view.findViewById(R.id.sp_diag_fzxs);
        sp_diag_gwxs=view.findViewById(R.id.sp_diag_gwxs);
        sp_diag_kyzt=view.findViewById(R.id.sp_diag_kyzt);

        Button btn_diag_save= view.findViewById(R.id.btn_diag_save);
        Button btn_diag_canecl= view.findViewById(R.id.btn_diag_canecl);

        ArrayList<String>  fzxs_list=new ArrayList<>();
        fzxs_list.add("地上");
        fzxs_list.add("地下");
        ArrayList<String>  gwxs_list=new ArrayList<>();
        gwxs_list.add("环状");
        gwxs_list.add("支状");
        ArrayList<String>  kyzt_list=new ArrayList<>();
        kyzt_list.add("正常");
        kyzt_list.add("不正常");

        fzxs_adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, fzxs_list);
        gwxs_adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, gwxs_list);
        kyzt_adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, kyzt_list);
        sp_diag_fzxs.setAdapter(fzxs_adapter);
        sp_diag_gwxs.setAdapter(gwxs_adapter);
        sp_diag_kyzt.setAdapter(kyzt_adapter);


        ed_diag_locy.setText(gi.getGlon());
        ed_diage_locx.setText(gi.getGlat());
//        ed_diag_hight.setText(gi.getHight());


//        if (gi.getXfsbh()!=null){
//            ed_diag_xfsbh.setText(gi.getXfsbh());
//        }

        ed_diag_xfsbh.setText("XFSBH"+db_rq+db_count);
        ed_diag_wzms.setText(gi.getAddress());
//        ed_diag_jdmc.setText(gi.getAddress());
        if (gi.getHight()!=null){
//            ed_diag_hight.setText(gi.getHight());
        }
        if (gi.getSdcskjkgg()!=null){

            ed_diag_sdwskgg.setText(gi.getSdcskjkgg());
        }
        if (gi.getGwzj()!=null){

            ed_diag_gwzj.setText(gi.getGwzj());

        }
        if (gi.getGwyl()!=null){

            ed_diag_gwyl.setText(gi.getGwyl());
        }







        sp_diag_fzxs.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {


                fzxs=parent.getItemAtPosition(position).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sp_diag_gwxs.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                gwxs=parent.getItemAtPosition(position).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sp_diag_kyzt.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                kyzt=parent.getItemAtPosition(position).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

//        DisplayMetrics dm = new DisplayMetrics();
//        WindowManager m = getWindowManager();
//        m.getDefaultDisplay().getMetrics(dm);
//        // 为获取屏幕宽、高
//        WindowManager.LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的參数值
//        p.height = (int) (dm.heightPixels * 0.6); //高度设置为屏幕的1.0
//        p.width = (int) (dm.widthPixels * 0.86); // 宽度设置为屏幕的0.85
//        p.alpha = 1.0f; // 设置本身透明度
//        p.dimAmount = 0.6f; // 设置黑暗度
//        dialog.getWindow().setAttributes(p);




        btn_diag_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {



                gi.setStatus("5");
                gi.setXfsbh(ed_diag_xfsbh.getText().toString());
                gi.setLocx(ed_diag_locy.getText().toString());
                gi.setLocy(ed_diage_locx.getText().toString());
                gi.setHight(ed_diag_hight.getText().toString());
                gi.setPlace(fzxs);
                gi.setSdcskjkgg(ed_diag_sdwskgg.getText().toString());
                gi.setGwzj(ed_diag_gwzj.getText().toString());
                gi.setGwyl(ed_diag_gwyl.getText().toString());
                gi.setGwxs(gwxs);
                gi.setKyzt(kyzt);
                gi.setJdmc(ed_diag_jdmc.getText().toString());
                gi.setWzms(ed_diag_wzms.getText().toString());
                gi.setBz(ed_diag_bz.getText().toString());



//                System.out.println("ed_diag_xfsbh.getText().toString()"+ed_diag_xfsbh.getText().toString());
                SharedPreferences.Editor editor = sharedPreferences.edit();
                db_count=db_count+1;
                editor.putInt("count",db_count);
                editor.commit();

                gpsadd(gi);
                gpslist.add(gi);


                intiview();

//                RMA=new GpsAddressItemAdater(mContext,gpslist);
////                RMA.notifyDataSetChanged();
////                lv_gps_local.setSelection(RMA.getCount());
//
//                lv_gps_local.setAdapter(RMA);
                dialog.dismiss();
            }
        });

        btn_diag_canecl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    public void showDialog_db_clear1(){

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("是否导出数据");// 设置标题
        // builder.setIcon(R.drawable.ic_launcher);//设置图标
        builder.setMessage("数据保存在SD文件目录XFSBH文件夹下，导出后请查阅");// 为对话框设置内容
        // 为对话框设置取消按钮
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub

            }
        });
        // 为对话框设置中立按钮
        // builder.setNeutralButton("中立", new OnClickListener() {
        //
        // @Override
        // public void onClick(DialogInterface arg0, int arg1) {
        // // TODO Auto-generated method stub
        // myToast("您点击了中立按钮");
        // }
        // });
        // 为对话框设置确定按钮
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub

                exc_gpslist=initdata_load_ALL_asc();
                exportExcel(exc_gpslist);
                showDialog_db_clear2();
            }
        });
        builder.create().show();// 使用show()方法显示对话框

    }


    public void showDialog_db_clear2(){

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("是否清空数据库");// 设置标题
        // builder.setIcon(R.drawable.ic_launcher);//设置图标
        builder.setMessage("将初始化数据库，所有数据已经保存在EXC表");// 为对话框设置内容
        // 为对话框设置取消按钮
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub

            }
        });
        // 为对话框设置中立按钮
        // builder.setNeutralButton("中立", new OnClickListener() {
        //
        // @Override
        // public void onClick(DialogInterface arg0, int arg1) {
        // // TODO Auto-generated method stub
        // myToast("您点击了中立按钮");
        // }
        // });
        // 为对话框设置确定按钮
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub

            Toast.makeText(getApplicationContext(), "数据库初始化成功", Toast.LENGTH_SHORT).show();
//
                String sql3 = "delete from gpsaddress";
//                String sql4="update sqlite_sequence set seq=0 where name='gpsaddress";
                function.delete(mContext,new String[]{},sql3);
//                function.update(mContext,new String[]{},sql4);

            }
        });
        builder.create().show();// 使用show()方法显示对话框

    }

    public void gpsadd(gpsitem gi){

        //address VARCHAR,TIME TEXT,glat TEXT,glon TEXT,blat TEXT,blon TEXT,Status TEXT

        /*
         * id INTEGER PRIMARY KEY AUTOINCREMENT,
         * xfsbh TEXT,
         * address TEXT,
         * TIME TEXT,
         * glat TEXT,
         * glon TEXT,
         * blat TEXT,
         * blon TEXT,
         * Status TEXT,
         * locx TEXT,
         * locy TEXT,
         * hight TEXT,
         * place TEXT,
         * sdcskjkgg TEXT,
         * gwzj TEXT,
         * gwyl TEXT,
         * gwxs TEXT,
         * kyzt TEXT,
         * jdmc TEXT,
         * wzms TEXT,
         * bz TEXT
         * */
        String sql = "insert into "+gpsaddress+" (xfsbh,address,TIME,glat,glon,blat,blon,Status,locx,locy,hight,place,sdcskjkgg,gwzj,gwyl,gwxs,kyzt,jdmc,wzms,bz) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        Object[] data = {gi.getXfsbh(),gi.getAddress(),gi.getTime(),gi.getGlat(),gi.getGlon(),gi.getBlat(),gi.getBlon(),gi.getStatus(),gi.getLocx(),gi.getLocy(),gi.getHight(),gi.getPlace(),gi.getSdcskjkgg(),gi.getGwzj(),gi.getGwyl(),gi.getGwxs(),gi.getKyzt(),gi.getJdmc(),gi.getAddress(),gi.getBz()};
        function.insert(mContext,data,sql);
    }


    //初始化编号
    public String NewXFSBH(String x){
        /*
        * 默认编号 XHSBH 时间戳？
        * 编码生成格式
        * 时间 XHSBH202009050001?
        *
        * */



        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");// HH:mm:ss
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        String name="XHSBH"+simpleDateFormat.format(date);

        return  name;
    }


    /**
     * 导出excel
     */
    public void exportExcel(List<gpsitem> glist) {



        String[] title = { "ID","消防栓编号","地址","时间","维度","经度","高度","放置形式","水袋出水口规格","管网直径(mm)","管网压力(Mpa)","管网形式(环状/支状)","可用状态","街道名称","位置描述","备注"};

        File file = new File(ExcelUtil.getSDPath() + "/xfsbhfile");
        System.out.println("file path"+file.toString());

        ExcelUtil.makeDir(file);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());//Calendar.getInstance().toString();

        String testId="XFSBH";

        String fileName = file.toString() + "/"+testId+"-"+time+".xls";
        System.out.println("fileName  "+ fileName);
        ExcelUtil.initExcel(fileName, title);

        ExcelUtil.writeObjListToExcel(getRecordData(glist), fileName, this);
    }

    /**
     * 将数据集合 转化成ArrayList<ArrayList<String>>
     * @return
     */


    /*
     * id INTEGER PRIMARY KEY AUTOINCREMENT,
     * xfsbh TEXT,
     * address TEXT,
     * TIME TEXT,
     * glat TEXT,
     * glon TEXT,
     * blat TEXT,
     * blon TEXT,
     * Status TEXT,
     * locx TEXT,
     * locy TEXT,
     * hight TEXT,
     * place TEXT,
     * sdcskjkgg TEXT,
     * gwzj TEXT,
     * gwyl TEXT,
     * gwxs TEXT,
     * kyzt TEXT,
     * jdmc TEXT,
     * wzms TEXT,
     * bz TEXT
     * */

    private  ArrayList<ArrayList<String>> getRecordData(List<gpsitem> glist) {
        ArrayList<ArrayList<String>> recordList = new ArrayList<>();
        for (int i = 0; i <glist.size(); i++) {
            ArrayList<String> beanList = new ArrayList<String>();
            beanList.add(String.valueOf(glist.get(i).getId()));
            beanList.add(String.valueOf(glist.get(i).getXfsbh()));
            beanList.add(String.valueOf(glist.get(i).getAddress()));
            beanList.add(String.valueOf(glist.get(i).getTime()));
            beanList.add(String.valueOf(glist.get(i).getGlat()));
            beanList.add(String.valueOf(glist.get(i).getGlon()));
            beanList.add(String.valueOf(glist.get(i).getHight()));
            beanList.add(String.valueOf(glist.get(i).getPlace()));
            beanList.add(String.valueOf(glist.get(i).getSdcskjkgg()));
            beanList.add(String.valueOf(glist.get(i).getGwzj()));
            beanList.add(String.valueOf(glist.get(i).getGwyl()));
            beanList.add(String.valueOf(glist.get(i).getGwxs()));
            beanList.add(String.valueOf(glist.get(i).getKyzt()));
            beanList.add(String.valueOf(glist.get(i).getJdmc()));
            beanList.add(String.valueOf(glist.get(i).getWzms()));
            beanList.add(String.valueOf(glist.get(i).getBz()));


            recordList.add(beanList);
        }
        return recordList;
    }



}
